package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItem;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderForm;
import com.scalar.chiptrack.operations.process.ProcessTypes;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.utils.Logger;

/**
 * Author: Phani Raja Kumar
 * Date  : Feb 20, 2005
 * Time  : 12:09:17 AM
 */
public class PurchaseOrderLoadCommand extends ChipTrackExtendedAction
{

    public ActionForward executeRequest( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)	throws ScalarException
    {
        HashMap errors			= ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info            = ( HashMap ) request.getAttribute( INFO_MESSAGES );
        String actionForward 	= "Search";
        HttpSession mSession 	= request.getSession();
        PurchaseOrderForm purchaseOrderForm = ( PurchaseOrderForm ) form;
        Iterator lineItemIterator           = null;
        String searchType = request.getParameter("searchType");
        request.setAttribute( "searchType", searchType);


        try
        {
            if ( "searchCancelledPurchaseOrder".equals(searchType) )
            {
                purchaseOrderForm = PurchaseOrderDAO.loadCancelledPurchaseOrder( purchaseOrderForm );
            }
            else
            {
                purchaseOrderForm = PurchaseOrderDAO.loadPurchaseOrder( purchaseOrderForm );
            }
            purchaseOrderForm.setShippingMethodsList( NewCustomerDAO.loadAllShippingMethods ( null, -1 ) );
            purchaseOrderForm.setPayTermsList( SalesDAO.getAllShippingTerms() );
            purchaseOrderForm.setTotalAsInDatabase( purchaseOrderForm.getTotal());
            Vendor vendor = VendorDAO.getVendorDetails( purchaseOrderForm.getVendor_id() );
            purchaseOrderForm.setVendorName( vendor.getVendorName() );

			purchaseOrderForm.setBillingAddress( PurchaseOrderDAO.getClientAddress() );
			purchaseOrderForm.setShippingAddress( PurchaseOrderDAO.getAddress( purchaseOrderForm.getShippingAddress_id() ) );


            /*purchaseOrderForm.setBillingAddress( PurchaseOrderDAO.getClientAddress() );
            purchaseOrderForm.setBillingAddress_id( PurchaseOrderDAO.getClientAddress().getAddressId() );
            purchaseOrderForm.setShippingAddress( ((Location)vendor.getLocationsList().get( 0 )).getLocationAddress() );
            purchaseOrderForm.setShippingAddress_id( ((Location)vendor.getLocationsList().get( 0 )).getLocationAddress().getAddressId() );*/


            lineItemIterator = purchaseOrderForm.getPurchaseOrderLineItemList().iterator();

            while ( lineItemIterator.hasNext() )
            {
                PurchaseOrderLineItem purchaseOrderLineItem = ( PurchaseOrderLineItem ) lineItemIterator.next();

                String processType = null;
                boolean exists     = false;

                processType                = purchaseOrderLineItem.getProcessName();
                ArrayList poPartNumberList = PurchaseOrderDAO.loadPartNumbersByVendorIdAndLocation( purchaseOrderForm.getVendor_id(), purchaseOrderLineItem.getProcessName() );

                if ( poPartNumberList != null )
                {
                    for(int i = 0; i < poPartNumberList.size(); i++ )
                    {
                        LabelValueBean labelValueBean = (LabelValueBean)poPartNumberList.get(i);

                        if ( labelValueBean.getLabel().equalsIgnoreCase( purchaseOrderLineItem.getPartNumber() ) )
                        {
                            exists = true;
                        }
                    }
                }
                if ( !exists )
                {
                    if( ( processType != null ) && ( ( ProcessTypes.sort.equalsIgnoreCase( processType ) )|| ( ProcessTypes.test.equalsIgnoreCase( processType ) ) ) )
                    {
                        poPartNumberList.add( new LabelValueBean( purchaseOrderLineItem.getPartNumber()+"/"+processType.toUpperCase(), purchaseOrderLineItem.getProcessStepId()+"" ) );
                    }
                    else
                    {
                        poPartNumberList.add( new LabelValueBean( purchaseOrderLineItem.getPartNumber(), purchaseOrderLineItem.getProcessStepId()+"" ) );
                    }
                }
                purchaseOrderLineItem.setPartNumbersList( poPartNumberList );

                //This snippet is used to add the messages indicating which line items have been cancelled.
                if( "searchPendingPurchaseOrder".equalsIgnoreCase(searchType) && purchaseOrderLineItem.getCancel() && PURCHASE_ORDER_STATUS_NEW.equalsIgnoreCase(purchaseOrderLineItem.getStatus()))
                {
                    errors.put( "LineItem No - " + purchaseOrderLineItem.getPurchaseOrderLineItemNumber(), " has been cancelled and needs approval" );
                }
            }

            request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
            request.setAttribute( "processNameList", PurchaseOrderDAO.loadProcessNames( purchaseOrderForm.getVendor_id() ) );
            request.setAttribute( "packageTypeList", PurchaseOrderDAO.loadPackageTypeList() );
            request.setAttribute( "financeReasonCodes", PurchaseOrderDAO.loadFinanceHolds() );
            request.setAttribute( "opsReasonCodes", PurchaseOrderDAO.loadOperationsHolds() );
            request.setAttribute( "poTaxes", PurchaseOrderDAO.loadPOTaxesList () );
            actionForward = "load";
            if( searchType != null )
            {
                if( "searchViewPurchaseOrder".equals(searchType) || "searchCancelledPurchaseOrder".equals(searchType))
                {
                    actionForward = "viewPO";
                }
            }
        }
        catch ( Exception e )
        {
            Logger.error( ERROR_SAVING_PURCHASE_ORDER_INFORMATION, e );
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "" );
            mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while executing the command", e ) );
            actionForward = "Search";
        }

        request.setAttribute( ERROR_MESSAGES, errors );
        request.setAttribute( INFO_MESSAGES, info );
        return mapping.findForward( actionForward );
    }

}
